package com.xd.navi;

import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneUtils {

    /**
     * 测量View的宽高
     *
     * @param view View
     */
    public static void measureWidthAndHeight(View view) {
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    }

    public  static String formatamount(double amount){
        NumberFormat nf = new DecimalFormat("##.##");
        String str = nf.format(amount);
        return  str;
    }


    /**
     * 格式化金额，保留2位小数点
     * @param amount
     * @return
     */
    public  static String fromatAmount(double amount){
        if (amount == 0 || amount == 0.0) {
            return "0.00";
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return  decimalFormat.format(Double.valueOf(((amount*100)/100f)));
    }

    public  static String fromatAmount(String amount){
        if (TextUtils.isEmpty(amount)) {
            return "0.00";
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        double _amount = Double.valueOf(amount);
        return  decimalFormat.format(Double.valueOf(((_amount*100)/100f)));
    }

    public  static String fromatMiusAmount(String amount){
        if (TextUtils.isEmpty(amount)) {
            return "0.00";
        }else if (amount.equals("0.0")){
            amount = "0.00";
        }
        if (amount.contains(".")){  //15.00
            String[] v = amount.split(".");
            String s = v[0];
            Log.e("---", "fromatMiusAmount: "+v.length+"/s="+s );
            if (v.length >= 2){
                if (v[1].length() >2){
                    s = v[1].substring(0, v[1].length() - 1);
                }
            }
            amount = s;
        }
        long  _amount = Long.valueOf(amount);
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        return  decimalFormat.format(Double.valueOf((_amount/100f)));
    }

    /**
     * 将系统时间转换成年月日 时分秒
     * @param time
     * @return
     */
    public static String formatMillisecondAllDate(long time) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date(time);
        String strDate = format.format(date);
        return strDate;
    }

    public  static String formatDate(long time){
        long hours = (time%(1000*60*60*24))/(1000*60*60);
        long minuter = (time%(1000*60*60))/(1000*60);
        long seconds  =  (time%(1000*60))/(1000);
        return  hours+"小时"+minuter+"分钟"+seconds+"秒";
    }

    /**
     * dp转换成px
     */
    public static int dp2px(Context context, float dpValue){
        float scale=context.getResources().getDisplayMetrics().density;
        return (int)(dpValue*scale+0.5f);
    }

    /**
     * px转换成dp
     */
    public static int px2dp(Context context, float pxValue){
        float scale=context.getResources().getDisplayMetrics().density;
        return (int)(pxValue/scale+0.5f);
    }
    /**
     * sp转换成px
     */
    public static int sp2px(Context context, float spValue){
        float fontScale=context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue*fontScale+0.5f);
    }
    /**
     * px转换成sp
     */
    public static int px2sp(Context context, float pxValue){
        float fontScale=context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue/fontScale+0.5f);
    }


    /**
     * 验证手机号码
     */
    public static boolean checkTel( String string) {
        if (TextUtils.isEmpty(string)) return false;
        String patternStr = "^1[3|4|5|7|8|9][0-9]\\d{8}$";
        Pattern p = Pattern.compile(patternStr);
        Matcher m = p.matcher(string);
        return m.matches();
    }


    /**
     * 判断6-18位字母或数字的密码
     * @param password
     * @return
     */
    public  static  boolean isPassword(String password){
        if (!TextUtils.isEmpty(password)){
            String patternStr = "^[0-9a-zA-Z]{6,18}$";
            Pattern p = Pattern.compile(patternStr);
            Matcher m = p.matcher(password);
            return m.matches();
        }
        return  false;
    }
    /**
     * 判断2次密码是否一致
     */
    public  static  boolean isSamePwd(String pwd1, String pwd2){
        if (!TextUtils.isEmpty(pwd1)){
            if (pwd1.equals(pwd2)){
                return  true;
            }
        }
        return false;
    }

    /**
     * 检查是否存在刘海屏
     * @param context
     * @return
     */
    public static boolean hasNotchInScreen(Context context) {
        boolean ret = false;
        try {
            ClassLoader cl = context.getClassLoader();
            Class HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
            Method get = HwNotchSizeUtil.getMethod("hasNotchInScreen");
            ret = (boolean) get.invoke(HwNotchSizeUtil);
        } catch (ClassNotFoundException e) {
            Log.e("test", "hasNotchInScreen ClassNotFoundException");
        } catch (NoSuchMethodException e) {
            Log.e("test", "hasNotchInScreen NoSuchMethodException");
        } catch (Exception e) {
            Log.e("test", "hasNotchInScreen Exception");
        } finally {
            return ret;
        }
    }

    /**
     * 获取刘海屏参数
     * @param context
     * @return
     */
    public static int[] getNotchSize(Context context) {
        int[] ret = new int[]{0, 0};
        try {
            ClassLoader cl = context.getClassLoader();
            Class HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
            Method get = HwNotchSizeUtil.getMethod("getNotchSize");
            ret = (int[]) get.invoke(HwNotchSizeUtil);
        } catch (ClassNotFoundException e) {
            Log.e("test", "getNotchSize ClassNotFoundException");
        } catch (NoSuchMethodException e) {
            Log.e("test", "getNotchSize NoSuchMethodException");
        } catch (Exception e) {
            Log.e("test", "getNotchSize Exception");
        } finally {
            return ret;
        }
    }

    /**
     * 获取系统状态栏高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 判断服务是否被杀死
     * @param serviceName
     * @param context
     * @return
     */
    private boolean serviceAlive(String serviceName, Context context) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    /** 判断程序是否在后台运行 */
    public static boolean isRunBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 表明程序在后台运行
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }

}
